﻿using System;
using System.Collections.Generic;
using System.Text;
using System.Reflection;
using System.IO;
using IApp = app_plugin_api;      //主程序接口命名空间

namespace app_plugin_main
{
    /// <summary>
    /// 插件管理器
    /// </summary>
    public class PluginManage
    {
        public PluginManage()
        {
            LoadAllPlugins();
        }

        /// <summary>
        /// 插件集合
        /// </summary>
        public List<IApp.IPluginAPI> plugs = new List<app_plugin_api.IPluginAPI>();

        /// <summary>
        /// 加载全部插件
        /// </summary>
        private void LoadAllPlugins()
        {
            string dir = Path.Combine(AppDomain.CurrentDomain.BaseDirectory, "Plugin");
            if (!Directory.Exists(dir)) return;

            DirectoryInfo dirInfo = new DirectoryInfo(dir);
            FileInfo[] dlls = dirInfo.GetFiles("*.dll");

            foreach (FileInfo file in dlls)
            {
                Assembly assembly = Assembly.LoadFile(file.FullName);
                try
                {
                    Type[] types = assembly.GetTypes();
                    foreach (Type type in types)
                    {
                        if (type.GetInterface("IPluginAPI") != null)
                        {
                            IApp.IPluginAPI instance = (IApp.IPluginAPI)Activator.CreateInstance(type);
                            
                            //将插件对象添加到List集合plugs
                            plugs.Add(instance);
                        }
                    }
                }
                catch { }
            }
        }
    }
}